import React from "react";
import back from "../../assets/images/login-bg.jpg";
import { Button, Form, Input, message as antdMessage } from "antd";
import { LoginState } from "../../types";
import _ from "lodash";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { l } from "../../utils/storage";

const Index: React.FC = () => {
  const navigate = useNavigate()
  const onFinish = async (value: LoginState) => {
    const resp = await axios.post("/api/login", value);
    
    const { code, message, data } = resp.data;
    if(code === 200) {
      antdMessage.success(message);
      navigate('/');
      l.setItem('userInfo', data.userInfo)
      l.setItem('token', data.token)
    } else {
      antdMessage.error(message)
    }
  };
  return (
    <div className="login" style={{ backgroundImage: `url(${back})` }}>
      <div className="login-box">
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={_.debounce(onFinish, 200)}
        >
          <Form.Item wrapperCol={{ span: 24 }}>
            <h3 style={{ textAlign: "center" }}>用户登录</h3>
          </Form.Item>
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: "用户名/手机号/邮箱地址 不可以为空",
              },
              {
                pattern:
                  /^([a-zA-Z][\da-zA-Z]{4,12})|(1[3-9]\d{9})|(\w+@\w+\.(com|cn|net))$/,
                message: "用户名/手机号/邮箱地址 格式不正确",
              },
            ]}
          >
            <Input placeholder="请输入用户名/手机号/邮箱地址"></Input>
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: "密码 不可以为空",
              },
              {
                pattern: /^\w{5,12}$/,
                message: "密码必须由6-12位数字、字母、下划线组成",
              },
            ]}
          >
            <Input.Password></Input.Password>
          </Form.Item>
          <Form.Item wrapperCol={{ span: 20, offset: 4 }}>
            <Button block type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Index;
